import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpSend implements Runnable {
    private String host;// 往哪发
    private int port;// 发的哪个端口上
    private Scanner scanner;
    private InetAddress address;
    private DatagramSocket socket;

    public UdpSend(String host, int port) throws UnknownHostException, SocketException {
        this.host = host;
        this.port = port;
        this.scanner = new Scanner(System.in);
        this.address = InetAddress.getByName(host);
        this.socket = new DatagramSocket();


    }

    @Override
    public void run() {
        while (true) {
            System.out.println("请输入要发的内容：");
            String content = scanner.next();
            DatagramPacket datagramPacket = new DatagramPacket(content.getBytes(), 0, content.getBytes().length, this.address, port);
            try {
                this.socket.send(datagramPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
